package com.kmdd.xtds.configs

import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.flow.MutableStateFlow

object PrefsManager {

    private lateinit var kv: MMKV


    private const val VALUE_BLOOD_RECORD = "VALUE_BLOOD_RECORD"


    /**
     * 血糖记录 流
     */
    val bloodRecordFlow by lazy { MutableStateFlow(bloodValue) }


    fun load(context: Context) {
        MMKV.initialize(context)
        kv = MMKV.defaultMMKV()
    }

    fun saveShrink(shrink: String) {
        kv.encode("shrink", shrink)
    }

    fun getShrink(): String = kv.decodeString("shrink") ?: "0"

    fun saveDiastolicBloodPressure(diastolicBloodPressure: String) {
        kv.encode("diastolicBloodPressure", diastolicBloodPressure)
    }

    fun getDiastolicBloodPressure(): String =
        kv.decodeString("diastolicBloodPressure") ?: "0"

    fun saveBloodOxygenSaturation(bloodOxygenSaturation: String) {
        kv.encode("bloodOxygenSaturation", bloodOxygenSaturation)
    }

    fun getBloodOxygenSaturation(): String =
        kv.decodeString("bloodOxygenSaturation") ?: "0"


    /**
     * 血糖值
     */
    var bloodValue: BloodRecord
        get() {
            val bloodRecordJson = kv.decodeString(VALUE_BLOOD_RECORD) ?: return BloodRecord(
                "", "0", "0"
            )
            Log.d("PrefsManager", "数据映射:${bloodRecordJson}")
            return Gson().fromJson(bloodRecordJson, BloodRecord::class.java) ?: BloodRecord(
                "", "0", "0"
            )
        }
        set(value) {
            bloodRecordFlow.value = value
            kv.encode(VALUE_BLOOD_RECORD, Gson().toJson(value))
        }

    fun saveAgreement(result: Boolean) {
        kv.encode("Agreement", result)
    }

    fun getAgreement() = kv.getBoolean("Agreement", false)
}